package org.tinygroup.dbcluster.algorithm.jdbc.util;

import org.tinygroup.commons.tools.Resources;
import org.tinygroup.dbrouter.RouterManager;
import org.tinygroup.dbrouter.config.ConnectionGet;
import org.tinygroup.dbrouter.config.DataSourceConfig;
import org.tinygroup.dbrouter.config.Router;
import org.tinygroup.tinytestutil.script.ScriptRunner;

import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.*;

/**
 * Created by wangwy11342 on 2015/11/26.
 */
public class DbrouterConnectionUtil {
    private static Map<String,String> dsurl = null;
    public static void initDDL(RouterManager routerManager) {
        dsurl = new HashMap<String, String>();
        dsurl.put("com.mysql.jdbc.Driver","jdbc:mysql://mysqldb:3306/%s");
        dsurl.put("org.apache.derby.jdbc.EmbeddedDriver","jdbc:derby:%s;create=true");
        dsurl.put("org.apache.derby.jdbc.ClientDriver","jdbc:derby:%s;create=true");
        DataSourceConfig dataSourceConfig = getFirstRouterConfig(routerManager);
        String driver = dataSourceConfig.getDriver();
        if(driver!=null){
            String urlbase = dsurl.get(driver);
            if(urlbase.indexOf("derby")<0) return;
            if(urlbase==null) return;
            try {
                Class.forName(driver);
                 /*
            * 初始化test0/test1/test2
            * */
                String username = dataSourceConfig.getUserName();
                String password = dataSourceConfig.getPassword();
                String url =  String.format(urlbase,"test0");
                runScript(url,username,password, "table_testx.sql");
                url =  String.format(urlbase,"test1");
                runScript(url,username,password, "table_testx.sql");
                url =  String.format(urlbase,"test2");
                runScript(url,username,password, "table_testx.sql");

                url =  String.format(urlbase,"test");
                runScript(url,username,password, "table_test.sql");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private static void runScript(String url,String username,String password,String sqlfile) throws Exception {
        Connection conn = DriverManager.getConnection(url,username,password);
        ScriptRunner derbyrunner = new ScriptRunner(conn, false, false);
        Resources.setCharset(Charset.forName("utf-8"));
        derbyrunner.runScript(Resources.getResourceAsReader(sqlfile));
    }

    /**
     * 获取第一个router节点
     * @return
     */
    private static DataSourceConfig getFirstRouterConfig(RouterManager routerManager){
        Collection<Router> routers = routerManager.getRouterMap().values();
        Iterator<Router> iterator = routers.iterator();
        if(iterator.hasNext()){
            Router router = iterator.next();
            List<ConnectionGet> dsconfigs = router.getDataSources();
            return (dsconfigs !=null && dsconfigs.size()>=0) ? (DataSourceConfig)dsconfigs.get(0):null;
        }
        return null;
    }

}
